package com.lanou.myapp.news.gamanews;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.lanou.myapp.R;
import com.lanou.myapp.imageloader.VolleySingleton;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dllo on 16/1/10.
 */
public class GameNewsFragment extends Fragment{
    private Context context;
    private RecyclerView recyclerView;
    private List<GameNews> data;
    private RecyclerGameAdapter adapter;
    private String url = "http://dailyapi.ibaozou.com/api/v1/section/27";

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        recyclerView = (RecyclerView) getActivity().findViewById(R.id.recyclerView_game_news);
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                GameNewsBeans beans = gson.fromJson(response, GameNewsBeans.class);
                data = new ArrayList<>();
                for (int i = 0; i < beans.getArticles().size(); i++) {
                    data.add(beans.getArticles().get(i));
                }

                adapter = new RecyclerGameAdapter(context,data);
                recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                recyclerView.setAdapter(adapter);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        VolleySingleton.getInstance()._addRequest(request);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(context).inflate(R.layout.fragment_game,null);
        return view;
    }
}
